package com.lx.service.impl;

import com.lx.Constants;
import com.lx.dao.*;
import com.lx.model.*;
import com.lx.service.MessageService;
import javafx.concurrent.Task;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Transactional
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private PrintDishTypeMapper printDishTypeMapper;
    @Autowired
    private PrintTableInfoMapper printTableInfoMapper;
    @Autowired
    private PrintShopDishMapper printShopDishMapper;
    @Autowired
    private PrintTableAreaMapper printTableAreaMapper;
    @Autowired
    private PrintTableTypeMapper printTableTypeMapper;
    @Autowired
    private PrintOrderInfoMapper printOrderInfoMapper;
    @Autowired
    private PrintOrderDishMapper printOrderDishMapper;
    @Autowired
    private PrintTaskMapper printTaskMapper;
    @Autowired
    private PrintTaskDetailMapper printTaskDetailMapper;
    @Autowired
    private PrintTablePlanMapper printTablePlanMapper;
    @Autowired
    private PrintDishPlanMapper printDishPlanMapper;
    @Autowired
    private PrintPlanMapper printPlanMapper;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public void saveDishType(PrintDishType printDishType) {
        PrintDishType printDishTypeDB = printDishTypeMapper.selectByPrimaryKey(printDishType.getId());
        printDishType.setUpdateTime(new Date());
        if(printDishTypeDB == null) {
            printDishType.setCreateTime(new Date());
            printDishTypeMapper.insert(printDishType);
        } else {
            printDishTypeMapper.updateByPrimaryKeySelective(printDishType);
        }
    }

    @Override
    public void savePrintTableInfo(PrintTableInfo printTableInfo) {
        PrintTableInfo printTableInfoDB = printTableInfoMapper.selectByPrimaryKey(printTableInfo.getId());
        printTableInfo.setUpdateTime(new Date());
        if(printTableInfoDB == null) {
            printTableInfo.setCreateTime(new Date());
            printTableInfoMapper.insert(printTableInfo);
        } else {
            printTableInfoMapper.updateByPrimaryKeySelective(printTableInfo);
        }
    }

    @Override
    public void savePrintShopDish(PrintShopDish printShopDish) {
        logger.info((printShopDish.getId()).toString());
        PrintShopDish printShopDishDB = printShopDishMapper.selectByPrimaryKey(printShopDish.getId());
        printShopDish.setUpdateTime(new Date());
        if(printShopDishDB == null) {
            printShopDish.setCreateTime(new Date());
            printShopDishMapper.insert(printShopDish);
        } else {
            printShopDishMapper.updateByPrimaryKeySelective(printShopDish);
        }
    }

    @Override
    public void savePrintTableArea(PrintTableArea printTableArea) {
        PrintTableArea printTableAreaDB = printTableAreaMapper.selectByPrimaryKey(printTableArea.getId());
        printTableArea.setUpdateTime(new Date());
        if(printTableAreaDB == null){
            printTableArea.setCreateTime(new Date());
            printTableAreaMapper.insert(printTableArea);
        } else {
            printTableAreaMapper.updateByPrimaryKeySelective(printTableArea);
        }
    }

    @Override
    public void savePrintTableType(PrintTableType printTableType) {
        PrintTableType printTableTypeDB = printTableTypeMapper.selectByPrimaryKey(printTableType.getId());

        printTableType.setUpdateTime(new Date());
//        printTableType.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));

        if(printTableTypeDB == null){
            printTableType.setCreateTime(new Date());
//            printTableType.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
            printTableTypeMapper.insert(printTableType);
        }else{
            //MQ会下发此字段，特殊处理
            printTableType.setUpdateTime(printTableTypeDB.getUpdateTime());
            printTableTypeMapper.updateByPrimaryKeySelective(printTableType);
        }
    }

    @Override
    public void savePrintOrderInfo(PrintOrderInfo info) {
        info.setCreateTime(new Date());
        info.setUpdateTime(new Date());
        printOrderInfoMapper.insert(info);
        if(info.getDishs()!=null){
            info.getDishs().forEach(d->{
                d.setOrderId(info.getId());
                d.setGoodsPrice(d.getPrice());
                printOrderDishMapper.insert(d);
            });
        }
        //处理账单任务 开始
        PrintTask billTask = createPrintTask(info,"1");
        PrintTablePlan tablePlan = printTablePlanMapper.selectByTableNo(billTask.getShopId(),billTask.getTableNo());
        if (tablePlan==null)return;
        if(Constants.YES_NO_CODE_YES.equals(tablePlan.getKitchenPrintFlag())) {
            billTask.setPrintPlanId(new Long(tablePlan.getPlanIdString()));
            printTaskMapper.insert(billTask);
            //Map<String,PrintTaskDetail> tcDishMap = new HashMap<>();
            if (info.getDishs() != null) {
                info.getDishs().forEach(d -> {
                    PrintTaskDetail detail = createTaskDetail(d);
                    detail.setTaskId(billTask.getId());
                    printTaskDetailMapper.insert(detail);
                /*if (!d.getGoodsId().equals(d.getProductId())){//套餐
                    if (tcDishMap.containsKey(d.getGoodsId())){
                        detail = tcDishMap.get(d.getGoodsId());
                        detail.setPracticeName(detail.getPracticeName()+"|"+d.getProductName());
                    }else {
                        detail = createTaskDetail(d);
                        detail.setTaskId(billTask.getId());
                        detail.setPracticeName(d.getProductName());
                    }
                }else {
                    detail = createTaskDetail(d);
                    detail.setTaskId(billTask.getId());
                    printTaskDetailMapper.insert(detail);
                }*/
                });
            /*if (!tcDishMap.isEmpty()){
                for (PrintTaskDetail d:tcDishMap.values())printTaskDetailMapper.insert(d);
            }*/
            }
            //处理账单任务 结束
        }
        //厨打单任务 开始
        if (info.getDishs()==null||info.getDishs().size()==0)return;
        List<Long> dishIds = new ArrayList<>();
        HashMap<Long,List<PrintOrderDish>> dishHashMap = new HashMap<>();
        info.getDishs().forEach(d->{
            dishIds.add(d.getProductId());
            if(dishHashMap.containsKey(d.getProductId())){
                dishHashMap.get(d.getProductId()).add(d);
            }else{
                List<PrintOrderDish> l = new ArrayList<>();
                l.add(d);
                dishHashMap.put(d.getProductId(),l);
            }
        });

        HashMap<Long,List<PrintOrderDish>> planDishHashMap = new HashMap<>();
        List<PrintDishPlan> dishPlans = printDishPlanMapper.selectByShopDishIds(dishIds);
        if (dishPlans==null)return;
        for (PrintDishPlan p:dishPlans){
            if (Constants.YES_NO_CODE_NO.equals(p.getPrintFlag()))continue;
            if (planDishHashMap.containsKey(new Long(p.getPlanIdString()))){
                planDishHashMap.get(new Long(p.getPlanIdString())).addAll(dishHashMap.get(p.getShopDishId()));
            }else {
                PrintPlan printPlan = printPlanMapper.selectByPrimaryKey(new Long(p.getPlanIdString()));
                if (printPlan==null)continue;
                if ("一菜一单".equals(printPlan.getKitchenPrintType())){
                    for(PrintOrderDish dd:dishHashMap.get(p.getShopDishId())) {
                        PrintTask kTask = createPrintTask(info, "2");
                        kTask.setPrintPlanId(printPlan.getId());
                        printTaskMapper.insert(kTask);
                        PrintTaskDetail d = createTaskDetail(dd);
                        d.setTaskId(kTask.getId());
                        printTaskDetailMapper.insert(d);
                    }
                }else {
                    List<PrintOrderDish> orderDishes = new ArrayList<>();
                    orderDishes.addAll(dishHashMap.get(p.getShopDishId()));
                    planDishHashMap.put(printPlan.getId(),orderDishes);
                }
            }
        }
        if (!planDishHashMap.isEmpty()){
            for(Long pid:planDishHashMap.keySet()){
                PrintTask kTask = createPrintTask(info,"2");
                kTask.setPrintPlanId(pid);
                printTaskMapper.insert(kTask);
                for(PrintOrderDish od:planDishHashMap.get(pid)){
                    PrintTaskDetail d = createTaskDetail(od);
                    d.setTaskId(kTask.getId());
                    printTaskDetailMapper.insert(d);
                }
            }
        }



    }

    private PrintTask createPrintTask(PrintOrderInfo info,String taskType){
        PrintTask billTask = new PrintTask();
        billTask.setPrintStatus("0");
        billTask.setOrderSn(info.getOrderSn());
        billTask.setPrintType(taskType);
        billTask.setShopId(info.getShopId());
        billTask.setTableName(info.getTableName());
        billTask.setTableNo(info.getTableNo());
        billTask.setUpdateTime(new Date());
        billTask.setCreateTime(new Date());
        return billTask;
    }

    private PrintTaskDetail createTaskDetail(PrintOrderDish dish){
        PrintTaskDetail detail = new PrintTaskDetail();
        detail.setGoodsId(dish.getGoodsId());
        detail.setGoodsName(dish.getGoodsName());
        detail.setNumber(dish.getNumber());
        detail.setDishUnitName(dish.getDishUnitName());
        detail.setSpecifications(dish.getSpecifications());
        detail.setGoodsPrice(dish.getGoodsPrice());
        detail.setProductId(dish.getProductId());
        detail.setProductName(dish.getProductName());
        detail.setOderingPro(dish.getOderingPro());
        detail.setProductPrice(dish.getProductPrice());
        return  detail;
    }
}
